package src;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

// 原继承 User，改为继承 BaseRole
public class Admin extends BaseRole {
    // 构造方法调用 BaseRole 的构造（保留 users 参数）
    public Admin(String userId, String username, String passwordHash, String role, LocalDateTime registrationTime, String phoneNumber) {
        super(userId, username, passwordHash, role, registrationTime, phoneNumber);
    }

    // 实现 BaseRole 的抽象方法：定义管理员菜单逻辑
    @Override
    public void showMenu() {
        // 定义菜单选项与操作的映射（键为选项号，值为对应方法）
        Map<Integer, Runnable> options = new HashMap<>();
        options.put(0, null);
        options.put(1, this::changeAdminPassword);
        options.put(2, this::resetUserPassword);
        options.put(3, this::viewSystemLog);
        options.put(4, this::listAllUsers);
        options.put(5, this::deleteUser);
        options.put(6, this::queryUser);
        options.put(7, this::addUser);
        options.put(8, this::modifyUser);

        // 调用 BaseRole 的通用菜单循环（标题 + 选项映射）
        menuLoop("管理员菜单", options);
    }

    // 实现 BaseRole 的抽象方法：返回选项名称
    @Override
    protected String getOptionName(int choice) {
        switch (choice) {
            case 0: return "返回上一级菜单（退出登录）";
            case 1: return "修改自身密码";
            case 2: return "重置非管理员用户密码";
            case 3: return "查看系统日志";
            case 4: return "列出所有用户信息";
            case 5: return "删除指定用户信息";
            case 6: return "查询用户信息";
            case 7: return "增加用户信息";
            case 8: return "修改用户信息";
            default: return "未知选项";
        }
    }

    private void changeAdminPassword() {
        System.out.print("请输入新密码: ");
        String newPassword = Input.getValidStringInput();
        String newPasswordHash = MD5Util.encrypt(newPassword);
        //this.setPasswordHash(newPasswordHash);
        for (User user : CinemaSystem.users) {
            if (user.getUserId().equals(this.getUserId())) {
                user.setPasswordHash(newPasswordHash);
                break;
            }
        }
        LocalDateTime now = LocalDateTime.now();
        Logger.log(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - 操作人: " + this.getUsername() + " - 修改自身密码");
        System.out.println("密码修改成功！");
    }

    private void resetUserPassword() {
        System.out.print("请输入要重置密码的用户名: ");
        String targetUsername = Input.getValidStringInput();
        User user = CinemaSystem.userMap.get(targetUsername);
        if (user != null && !user.getRole().equals("管理员")) {
            String defaultPasswordHash = MD5Util.encrypt("123456");
            user.setPasswordHash(defaultPasswordHash);
            user.setMustChangePassword(true);
            LocalDateTime now = LocalDateTime.now();
            Logger.log(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - 操作人: " + this.getUsername() + " - 重置非管理员用户 " + targetUsername + " 的密码");
            System.out.println("用户 " + targetUsername + " 的密码已重置为默认密码 123456，请提醒用户登录后修改。");
            return;
        }
        System.out.println("未找到该非管理员用户！");
    }

    private void viewSystemLog() {
        for (String log : CinemaSystem.logs) {
            System.out.println(log);
        }
    }

    private void listAllUsers() {
        System.out.println("\n=== 所有用户信息 ===");
        System.out.printf("%-10s %-15s %-10s %-20s %-15s\n", 
            "用户ID", "用户名", "角色", "注册时间", "手机号");
        for (User user : CinemaSystem.users) {
            System.out.printf("%-10s %-15s %-10s %-20s %-15s\n",
                user.getUserId(),
                user.getUsername(),
                user.getRole(),
                user.getRegistrationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
                user.getPhoneNumber());
        }
    }

    private void deleteUser() {
        System.out.println("\n=== 删除指定用户信息 ===");
        System.out.print("请输入要删除的用户ID或用户名: ");
        String input = Input.getValidStringInput();

        User userToDelete = CinemaSystem.userMap.get(input); // 先按用户名查找
        if (userToDelete == null) {
            // 按ID查找
            for (User user : CinemaSystem.users) {
                if (user.getUserId().equals(input)) {
                    userToDelete = user;
                    break;
                }
            }
        }

        if (userToDelete != null && userToDelete.getUsername().equals("admin")) {
            System.out.println("不能删除 admin 管理员账户！");
            return;
        }

        if (userToDelete == null) {
            System.out.println("未找到该用户！");
            return;
        }

        System.out.println("警告：你即将删除用户 " + userToDelete.getUsername() + " 的信息，是否继续？(Y/N)");
        String confirm = Input.getValidStringInput();
        if (confirm.equalsIgnoreCase("Y")) {
            CinemaSystem.users.remove(userToDelete);
            
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Logger.log(now.format(formatter) + " - 操作人: " + this.getUsername() + " - 删除" + userToDelete.getRole() + " " + userToDelete.getUsername());
            System.out.println("用户信息删除成功！");
        } else {
            System.out.println("删除操作已取消。");
        }
    }

    private void queryUser() {
        System.out.println("\n=== 查询用户信息 ===");
        System.out.println("1. 根据用户ID查询");
        System.out.println("2. 根据用户名查询");
        System.out.println("3. 查询所有用户信息");
        System.out.print("请选择查询方式: ");
        int choice = Input.getValidIntInput(1,3);

        switch (choice) {
            case 1:
                System.out.print("请输入用户ID: ");
                String userId = Input.getValidStringInput();
                for (User user : CinemaSystem.users) {
                    if (user.getUserId().equals(userId)) {
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        System.out.println("用户ID: " + user.getUserId() +
                                ", 用户名: " + user.getUsername() +
                                ", 用户注册时间: " + user.getRegistrationTime().format(formatter) +
                                ", 用户类型: " + user.getRole() +
                                ", 用户手机号: " + user.getPhoneNumber());
                        return;
                    }
                }
                System.out.println("未找到该用户！");
                break;
            case 2:
                System.out.print("请输入用户名: ");
                String username = Input.getValidStringInput();
                User user = CinemaSystem.userMap.get(username);
                if (user != null) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    System.out.println("用户ID: " + user.getUserId() +
                            ", 用户名: " + user.getUsername() +
                            ", 用户注册时间: " + user.getRegistrationTime().format(formatter) +
                            ", 用户类型: " + user.getRole() +
                            ", 用户手机号: " + user.getPhoneNumber());
                    return;
                }
                System.out.println("未找到该用户！");
                break;
            case 3:
                listAllUsers();
                break;
            default:
                System.out.println("无效的选择，请重新输入。");
        }
    }

    private void addUser() {
    while (true) {
        System.out.print("请输入新用户ID: ");
        String newUserId = Input.getValidStringInput();

        // 优化：通过userIds集合快速校验ID重复（O(1)时间复杂度）
        if (CinemaSystem.userIds.contains(newUserId)) {
            System.out.println("该用户ID已存在，请重新输入！");
            continue;
        }

        while (true) {
            System.out.print("请输入新用户名: ");
            String newUsername = Input.getValidStringInput();

            // 优化：通过userMap快速校验用户名重复（O(1)时间复杂度）
            if (CinemaSystem.userMap.containsKey(newUsername)) {
                System.out.println("该用户名已存在，请重新输入！");
                continue;
            }

            // 输入其他用户信息（角色、手机号等）
            System.out.println("请选择用户角色（管理员/经理/前台）: ");
            String newRole = Input.getValidRoleInput();  
            System.out.print("请输入用户手机号: ");
            String newPhoneNumber = Input.getValidPhoneNumberInput();

            // 创建新用户并添加到列表和集合中
            String defaultPasswordHash = MD5Util.encrypt("123456");  // 默认密码
            LocalDateTime now = LocalDateTime.now();
            User newUser = new User(newUserId, newUsername, defaultPasswordHash, newRole, now, newPhoneNumber);
            newUser.setMustChangePassword(true);  // 强制修改初始密码

            // 更新全局数据
            CinemaSystem.users.add(newUser);
            CinemaSystem.userMap.put(newUsername, newUser);  // 同步到用户名映射
            CinemaSystem.userIds.add(newUserId);  // 同步到用户ID集合

            // 记录日志
            Logger.log(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - 操作人: " + this.getUsername() + " - 增加用户 " + newUsername + "，角色为 " + newRole);
            System.out.println("用户 " + newUsername + " 已添加成功！");
            return;
        }
    }
}

    private void modifyUser() {
        System.out.print("请输入要修改的用户ID: ");
        String userId = Input.getValidStringInput();
        User userToModify = null;
        for (User user : CinemaSystem.users) {
            if (user.getUserId().equals(userId)) {
                userToModify = user;
                break;
            }
        }
        if (userToModify == null) {
            System.out.println("未找到该用户！");
            return;
        }

        System.out.println("正在修改用户: " + userToModify.getUsername());
        System.out.println("请选择要修改的信息项:");
        System.out.println("1. 密码");
        System.out.println("2. 角色");
        System.out.println("3. 手机号");
        System.out.print("请输入选择: ");

        int choice = Input.getValidIntInput(1,3);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        switch (choice) {
            case 1:
                System.out.print("请输入新密码: ");
                String newPassword = Input.getValidStringInput();
                String newPasswordHash = MD5Util.encrypt(newPassword);
                userToModify.setPasswordHash(newPasswordHash);
                userToModify.setMustChangePassword(false);
                System.out.println("密码已更新！");
                Logger.log(now.format(formatter) + " - 操作人: " + this.getUsername() + " - 修改用户 " + userToModify.getUsername() + " 的密码");
                break;
            case 2:
                System.out.print("请输入新角色 (经理/前台): ");
                String newRole = Input.getValidStringInput();
                userToModify.setRole(newRole);
                System.out.println("角色已更新为: " + newRole);
                Logger.log(now.format(formatter) + " - 操作人: " + this.getUsername() + " - 修改用户 " + userToModify.getUsername() + " 的角色为 " + newRole);
                break;
            case 3:
                System.out.print("请输入新手机号: ");
                String newPhone = Input.getValidPhoneNumberInput();
                userToModify.setPhoneNumber(newPhone);
                System.out.println("手机号已更新为: " + newPhone);
                Logger.log(now.format(formatter) + " - 操作人: " + this.getUsername() + " - 修改用户 " + userToModify.getUsername() + " 的手机号为 " + newPhone);
                break;
            default:
                System.out.println("无效选择！");
        }
    }
}